{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "b1e40233",
   "metadata": {},
   "outputs": [],
   "source": [
    "from flask import Flask\n",
    "\n",
    "app = Flask(__name__)\n",
    "\n",
    "@app.route('/')\n",
    "def hello_world():\n",
    "    return 'Hello, world!'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "e6d8ce87",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Usage: ipykernel_launcher.py [OPTIONS]\n",
      "Try 'ipykernel_launcher.py --help' for help.\n",
      "\n",
      "Error: No such option: --f\n"
     ]
    },
    {
     "ename": "SystemExit",
     "evalue": "2",
     "output_type": "error",
     "traceback": [
      "An exception has occurred, use %tb to see the full traceback.\n",
      "\u001b[1;31mSystemExit\u001b[0m\u001b[1;31m:\u001b[0m 2\n"
     ]
    }
   ],
   "source": [
    "import click\n",
    "\n",
    "@click.command()\n",
    "@click.option('--count', default = 1, help = 'Number of greetings.')\n",
    "@click.option('--name', prompt = 'Your name',\n",
    "              help = 'The person to greet.')\n",
    "def hello(count, name):\n",
    "    \"\"\"Simple program that greets NAME for a total of COUNT times.\"\"\"\n",
    "    for x in range(count):\n",
    "        click.echo('Hello %s!' % name)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    hello()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14740b14",
   "metadata": {},
   "source": [
    "- 装饰器所做的，只是在函数定义语句上方，直接添加用来修改函数行为的装饰器函数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "076eaeab",
   "metadata": {},
   "source": [
    "## 8.1 基础知识\n",
    "### 8.1.1 装饰器基础\n",
    "- 装饰器是一种通过包装目标函数来修改其行为的特殊高阶函数，绝大多数装饰器是利用函数的闭包原理实现的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "4e8993d8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\"random_sleep\", args: (), kwargs: {}\n",
      "time cost: 0.2656503999969573 seconds\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "import time\n",
    "def timer(print_args = False):\n",
    "    \"\"\"装饰器：打印函数耗时\n",
    "    :param print_args:是否打印方法名和参数， 默认为False\n",
    "    \"\"\"\n",
    "    def decorator(func):\n",
    "        def wrapper(*args, **kwargs):\n",
    "            st = time.perf_counter()\n",
    "            ret = func(*args, **kwargs)\n",
    "            if print_args:\n",
    "                print(f'\"{func.__name__}\", args: {args}, kwargs: {kwargs}')\n",
    "            print('time cost: {} seconds'.format(time.perf_counter() - st))\n",
    "            return ret\n",
    "        return wrapper\n",
    "    return decorator\n",
    "\n",
    "@timer(print_args=True)\n",
    "def random_sleep():\n",
    "    \"\"\"随机睡眠一会\"\"\"\n",
    "    time.sleep(random.random())\n",
    "random_sleep()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e6e27e1",
   "metadata": {},
   "source": [
    "### 8.1.2 使用functools.wraps()修饰包装函数\n",
    "- 在装饰器包装目标函数的过程中， 常会出现一些副作用，其中一种是丢失元数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "068f11c6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\"decorated\", args: (), kwargs: {}\n",
      "time cost: 0.2945224000000053 seconds\n",
      "None\n",
      "Counter: 1\n",
      "None\n",
      "Counter: 1\n",
      "None\n",
      "decorated\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "from functools import wraps\n",
    "import random, time\n",
    "def calls_counter(func):\n",
    "    \"\"\"装饰器：记录函数被调用了多少次\n",
    "    使用func.print_counter()可以打印统计到的信息\n",
    "    \"\"\"\n",
    "    counter = 0\n",
    "\n",
    "    def decorated(*arg, **kwargs):\n",
    "        nonlocal counter\n",
    "        counter+=1\n",
    "        return func(*arg, **kwargs)\n",
    "    \n",
    "    def print_counter():\n",
    "        print(f'Counter: {counter}')\n",
    "    \n",
    "    decorated.print_counter = print_counter\n",
    "    return decorated\n",
    "\n",
    "def timer(func):\n",
    "\n",
    "    @wraps(func)\n",
    "    def decorated(*args, **kwargs):\n",
    "        \"\"\"\"\"\"\n",
    "        st = time.perf_counter()\n",
    "        ret = func(*args, **kwargs)\n",
    "        print(f'\"{func.__name__}\", args: {args}, kwargs: {kwargs}')\n",
    "        print('time cost: {} seconds'.format(time.perf_counter() - st))\n",
    "        return ret\n",
    "    return decorated\n",
    "\n",
    "@timer\n",
    "@calls_counter\n",
    "def random_sleep1():\n",
    "    \"\"\"随机睡眠一会\"\"\"\n",
    "    time.sleep(random.random())\n",
    "\n",
    "print(random_sleep1())\n",
    "print(random_sleep1.print_counter())\n",
    "print(random_sleep1.print_counter())\n",
    "print(random_sleep1.__name__)\n",
    "print(random_sleep1.__doc__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c121b0af",
   "metadata": {},
   "source": [
    "### 8.1.3 实现可选参数装饰器\n",
    "- 使用装饰器时提供参数\n",
    "- 不提供参数，也需要使用括号调用装饰器\n",
    "- 使用仅限关键字，可以省略可选参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "33065e79",
   "metadata": {},
   "outputs": [],
   "source": [
    "def delayed_start(func = None, *, duration = 1):\n",
    "    \"\"\"装饰器：在执行被装饰函数前，等待一段时间\n",
    "    \n",
    "    :param duration:需要等待的秒数\n",
    "    \"\"\"\n",
    "    def decorator(_func):\n",
    "        def wrapper(*args, **kwargs):\n",
    "            print(f\"Wait for {duration} second before starting...\")\n",
    "            time.sleep(duration)\n",
    "            return func(*args, **kwargs)\n",
    "        \n",
    "        return wrapper\n",
    "    if func is None:\n",
    "        return decorator\n",
    "    else:\n",
    "        return decorator(func)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab96c573",
   "metadata": {},
   "source": [
    "### 8.1.4 用类实现装饰器（函数替换）\n",
    "- 某个对象是否能通过装饰器的形式使用只有一条判断标准，那就是decorator是不是可调用对象\n",
    "- 如果一个类实现了__call__魔法方法，那么他的示例会变成可调用对象"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "587e6eb8",
   "metadata": {},
   "outputs": [],
   "source": [
    "class timer:\n",
    "    \"\"\"装饰器：打印函数耗时\n",
    "    \n",
    "    :param print_args:是否打印方法名和参数，默认为False\n",
    "    \"\"\"\n",
    "    def __init__(self, print_args):\n",
    "        self.print_args = print_args\n",
    "    \n",
    "    def __call__(self, func):\n",
    "        @wraps(func)\n",
    "        def decorated(*args, **kwargs):\n",
    "            st = time.perf_counter()\n",
    "            ret = func(*args, **kwargs)\n",
    "            if self.print_args:\n",
    "                print(f'\"{func.__name__}\", args:{args}, kwargs:{kwargs}')\n",
    "            print('time cost: {} senconds'.format(time.perf_counter() - st))\n",
    "            return ret \n",
    "\n",
    "        return decorated"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d151d6b",
   "metadata": {},
   "source": [
    "- 用类实现装饰器（示例替换）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8f6ef988",
   "metadata": {},
   "outputs": [],
   "source": [
    "#实现无参数装饰器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76b57233",
   "metadata": {},
   "outputs": [],
   "source": [
    "class DelayedStart:\n",
    "    \"\"\"在执行被装饰函数前，等待一秒钟\"\"\"\n",
    "\n",
    "    def __init__(self, func):\n",
    "        update_wrapper(self, func)\n",
    "        self.func = func\n",
    "    \n",
    "    def __call__(self, *args, **kwargs):\n",
    "        print(f'Wait for 1 second before starting...')\n",
    "        time.sleep(1)\n",
    "        return self.func(*args, **kwargs)\n",
    "    \n",
    "    def eager_call(self, *args, **kwargs):\n",
    "        \"\"\"跳过等待，立刻执行被装饰函数\"\"\"\n",
    "        print('Call without delay')\n",
    "        return self.func(*args, **kwargs)\n",
    "    \n",
    "@DelayedStart\n",
    "def hello():\n",
    "    print(\"Hello World!\")\n",
    "\n",
    "print(hello())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98cbf3c7",
   "metadata": {},
   "source": [
    "2. 实现有参数的修饰器"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12d9f772",
   "metadata": {},
   "source": [
    "### 8.1.6 使用wrapt模块助力装饰器编写"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1a2454ec",
   "metadata": {},
   "source": [
    "## 8.2 编程建议\n",
    "### 8.2.1 了解装饰器的本质优势\n",
    "- 动态修改函数\n",
    "### 8.2.2 使用类装饰器替代元类\n",
    "### 8.2.3 别弄混装饰器和装饰器模式\n",
    "### 8.2.4 浅装饰器，深实现"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
